import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const DataForm = ({ state, onCancel, modal, onSubmit, ...formProps }) => {
  const { ruleStore: store } = useStore();
  const { show, record, toClose, index } = modal;
  const [rule] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');

  useEffect(() => {
    if (toClose?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      if (record) {
        editCtx.origin = _.cloneDeep(record);
        _.assign(rule, record);
      }
    })();
  }, []);

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(rule, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    const _type = store._uniqueBatch(toJS(rule), show, index);
    if (_type) {
      Message.error({ content: store._MESSAGE_TEXT[_type], duration: 7000 });
      return;
    }
    onSubmit?.(rule);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form {...formProps} value={rule} onChange={handleChange} colon useLabelForErrorMessage>
      <FieldsGrid
        formData={rule}
        mode={show}
        columns={1}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        fields={['batchId', 'startPoint', 'endPoint']}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(DataForm);
